//
//  HomeListVC.m
//  ZPSALE
//
//  Created by fei on 14-8-12.
//  Copyright (c) 2014年 self. All rights reserved.
//

#import "HomeListVC.h"
#import "HomeListCell.h"
#import "BrandListVC.h"
#import "JSBadgeView.h"
#import "MBProgressHUD.h"
#import "HomeListNewCell.h"
#import "UIImageView+WebCache.h"
#import "WelcomShowView.h"
#import "logOnViewController.h"
@interface HomeListVC () 
{
    NSMutableArray *startedSpecialArray;
    NSMutableArray *comingSpecialArray;
    NSMutableArray *collectionArray;
    int currentPage;
    BOOL isRefresh;
    BOOL firstLoading;
    BOOL isFirstAppear;
    JSBadgeView *badgeView_cart;
}
@end

@implementation HomeListVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    self.navigationController.navigationBar.barTintColor = ColorFromRGB(0xDC2c03);
    //登录验证，确保每次进入首页获得有效的token
    [[NSNotificationCenter defaultCenter] postNotificationName:StringForCheckLogin object:nil];
    [self requestBrandListDataFromNet];
    [self requestCollectedListArray];
    [self getNumberOfProductInShopBag];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = ColorFromRGB(0xEEEEEE);
    
    startedSpecialArray = [[NSMutableArray alloc] initWithCapacity:0];
    comingSpecialArray = [[NSMutableArray alloc] initWithCapacity:0];
    collectionArray = [[NSMutableArray alloc] initWithCapacity:0];
    firstLoading = YES;
    [self setNavigationItems];
    
    [self setCollectionViewRefreshView];
    isFirstAppear = NO;
    
    badgeView_cart = [[JSBadgeView alloc] initWithParentView:_rightButton alignment:JSBadgeViewAlignmentTopRight];
    badgeView_cart.userInteractionEnabled = NO;
    badgeView_cart.badgePositionAdjustment = CGPointMake(-2, 18);
    badgeView_cart.badgeBackgroundColor = [UIColor whiteColor];
    badgeView_cart.badgeTextColor = ColorFromRGB(0xDC2c03);
    badgeView_cart.hidden = YES;
    [self addLineAtTopView];
/*
    NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
    if (!isFirstAppear && [[userD objectForKey:@"isFirst"] boolValue]) {
        isFirstAppear = YES;
        [WelcomShowView showWelcomView];
        [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideWelcomView) userInfo:nil repeats:NO];
    }
*/
}
-(void)hideWelcomView {
    [WelcomShowView hide:NO];
}




-(void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
}

-(void)setCollectionViewRefreshView {
    
    headerView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, -_brandListCollectionView.frame.size.height, _brandListCollectionView.frame.size.width, _brandListCollectionView.frame.size.height)];
    headerView.delegate = self;
    [_brandListCollectionView addSubview:headerView];
}



-(void)requestBrandListDataFromNet {
    
    MBProgressHUD *rHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    rHUD.hidden = YES;
    if (firstLoading) {
        rHUD.hidden = NO;
        firstLoading = NO;
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *par = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"platform", nil];
    
    [manager GET:APIURL"sale/initSpecialList.json" parameters:par success:^(AFHTTPRequestOperation *operation,id resultObject) {
        
        [self clearListArray];
        if ([resultObject valueForKey:@"content"]) {
            NSDictionary *dict = resultObject[@"content"];
            if (dict[@"started"]) {
                NSDictionary *startD = dict[@"started"];
                [startedSpecialArray addObjectsFromArray:startD[@"result"]];
            }
            if (dict[@"coming"]) {
                NSDictionary *startD = dict[@"coming"];
                [comingSpecialArray addObjectsFromArray:startD[@"result"]];
            }
            
            
        }
        
        
        
        [rHUD hide:YES afterDelay:.2];

        [self resetRefreshAndLoadingMoreView];
        [_brandListCollectionView reloadData];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        rHUD.mode = MBProgressHUDModeText;
        rHUD.labelText = @"加载失败，请稍后再试...";
        [rHUD hide:YES afterDelay:1];
        
        [self resetRefreshAndLoadingMoreView];
    }];
    
}

//取收藏专题id列表
-(void)requestCollectedListArray {
    
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSString *memberId = dataDic[@"memberId"];
    NSString *token = dataDic[@"token"];
    if ([CheckLoginObject isLogin]) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *par = [NSDictionary dictionaryWithObjectsAndKeys:memberId,@"memberid",token,@"access_token",@"2",@"platform", nil];
        [manager POST:APIURL"sale/getCollection.json" parameters:par success:^(AFHTTPRequestOperation *operation,id resultObject) {
            if (collectionArray.count > 0) {
                [collectionArray removeAllObjects];
            }
            if ([resultObject[@"error_code"] intValue] > 0 ) {
                
            } else {
                if ([resultObject[@"count"] intValue] > 0) {
                    if (resultObject[@"specialids"]) {
                        [collectionArray addObjectsFromArray:resultObject[@"specialids"]];
                        if (collectionArray.count > 0) {
                            [_brandListCollectionView reloadData];
                        }
                    }
                }
            }
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            
        }];
    } else {
        
    }
}

-(void)clearListArray {
    if (startedSpecialArray.count > 0) {
        [startedSpecialArray removeAllObjects];
    }
    if (comingSpecialArray.count > 0) {
        [comingSpecialArray removeAllObjects];
    }
}

-(void)getNumberOfProductInShopBag {
    NSDictionary *paraDict;
    
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSString *memeberId = [dataDic valueForKey:@"memberId"];
    if ([CheckLoginObject isLogin]) {   //登录状态 且 token未过期
        paraDict = @{
                     @"memberid":memeberId
                     };
        
        AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
        
        [httpManager GET:APIURL"sale/getCartProductNum.json" parameters:paraDict success:^(AFHTTPRequestOperation *operation ,id resultObject){
            int  numOfProduct = [resultObject[@"cartNum"] intValue];
            if (numOfProduct == 0) {
                badgeView_cart.badgeText = @"0";
                badgeView_cart.hidden = YES;
            } else {
                badgeView_cart.badgeText = [NSString stringWithFormat:@"%d",numOfProduct];
                badgeView_cart.hidden = NO;
            }
        } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
            badgeView_cart.badgeText = @"0";
            badgeView_cart.hidden = YES;
        }];
    } else {
        //未登录,
        badgeView_cart.badgeText = @"0";
        badgeView_cart.hidden = YES;
    }
    
   
}

-(void)resetRefreshAndLoadingMoreView {
    
    [headerView egoRefreshScrollViewDataSourceDidFinishedLoading:_brandListCollectionView];
    
    isRefresh = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)addLineAtTopView {
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, _topImageView.frame.size.height-0.5, _topImageView.frame.size.width, 0.5)];
    imageV.backgroundColor = ColorFromRGB(0xE0E0E0);
    
    [_topImageView addSubview:imageV];
    
//    _topTitleLabel.textColor = ColorFromRGB(0xff0100);
}

-(void)setNavigationItems {
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    UILabel *label = [[UILabel alloc] initWithFrame:view.frame];
    label.text = @"奢侈品特卖";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:20];
    [view addSubview:label];
    self.navigationItem.titleView = view;
    
    
}

#pragma mark UICollectionView dataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return startedSpecialArray.count;
    }
    if (section == 2) {
        return comingSpecialArray.count;
    }
    return 0;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (startedSpecialArray.count == 0 && comingSpecialArray.count == 0) {
        return 0;
    }
    if (comingSpecialArray.count == 0) {
        return 1;
    }
    return 3;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGSize sectionSize = CGSizeMake(collectionView.frame.size.width, 30);
    if (section == 1) {
        sectionSize = CGSizeMake(collectionView.frame.size.width, 10);
    }
    return sectionSize;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row < startedSpecialArray.count) {
        return [self createListCellWithIndexPath:indexPath andCollectionVIew:collectionView];
    } else if (indexPath.section == 2 && indexPath.row < comingSpecialArray.count) {
        return [self createListNewCellWithIndexPaht:indexPath andCollectionVIew:collectionView];
    }
    return nil;
}

-(HomeListCell *)createListCellWithIndexPath:(NSIndexPath *)indexPath andCollectionVIew:(UICollectionView *)collectionView {
    HomeListCell *cell = (HomeListCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"homeListCell" forIndexPath:indexPath];
    NSDictionary *dict = [startedSpecialArray objectAtIndex:indexPath.row];

//    [cell.bannerImageView sd_setImageWithURL:dict[@"webImg"] placeholderImage:[UIImage imageNamed:@"homelist_noimage"]];
////    [cell.bannerImageView setImage:[UIImage imageWithContentsOfFile:path]];
//    [cell.brandImageView_s sd_setImageWithURL:dict[@"brandImg"] placeholderImage:[UIImage imageNamed:@"brand_noimage_s"] options:SDWebImageProgressiveDownload];
    
    [cell.bannerImageView sd_setImageWithURL:Return_imageUrl(dict[@"webImg"], 608) placeholderImage:[UIImage imageNamed:@"homelist_noimage"]];
    [cell.brandImageView_s sd_setImageWithURL:Return_imageUrl(dict[@"brandImg"], 100) placeholderImage:[UIImage imageNamed:@"brand_noimage_s"]];
    
    cell.brandInfoLabel.text = dict[@"word"];
    cell.brandPriceLabel.attributedText = [self returenDisCountString:[NSString stringWithFormat:@"%@",dict[@"sale"]] andUnit:@" 折起"];
    
    if (indexPath.row == 2) {
        
    }
    cell.brandIsTodayImage.hidden = NO;
    cell.countDownView.frame = CGRectMake(208, 0, 101, 18);
    [cell.countDownView setTimeWithTimeIntervalString:[NSString stringWithFormat:@"%@",dict[@"endTime"]] andType:CountDownView_JustShow];
    return cell;
}


-(HomeListNewCell *)createListNewCellWithIndexPaht:(NSIndexPath *)indexPath andCollectionVIew:(UICollectionView *)collectionView{
//    NSArray *array = [brandListArray objectAtIndex:indexPath.section];
    NSDictionary *dict = [comingSpecialArray objectAtIndex:indexPath.row];
    
    HomeListNewCell *cell = (HomeListNewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"homeListNewCell" forIndexPath:indexPath];
    
//    [cell.bannerImageView sd_setImageWithURL:dict[@"webImg"] placeholderImage:[UIImage imageNamed:@"homelist_noimage"]];
//    //    [cell.bannerImageView setImage:[UIImage imageWithContentsOfFile:path]];
//    [cell.brandImageView_s sd_setImageWithURL:dict[@"brandImg"] placeholderImage:[UIImage imageNamed:@"brand_noimage_s"] options:SDWebImageProgressiveDownload];
    
    [cell.bannerImageView sd_setImageWithURL:Return_imageUrl(dict[@"webImg"], 608) placeholderImage:[UIImage imageNamed:@"homelist_noimage"]];
    [cell.brandImageView_s sd_setImageWithURL:Return_imageUrl(dict[@"brandImg"], 100) placeholderImage:[UIImage imageNamed:@"brand_noimage_s"]];
    cell.brandSaleLabel.text = dict[@"word"];
    
    cell.brandCollectBtn.selected = [self isCollected:[NSString stringWithFormat:@"%@",dict[@"id"]]] ? YES:NO;
    cell.brandCollectBtn.tag = indexPath.row;
    [cell.brandCollectBtn addTarget:self action:@selector(collectBrandClicked:) forControlEvents:UIControlEventTouchUpInside];
    cell.brandDiscountLabel.attributedText = [self returenDisCountString:[NSString stringWithFormat:@"%@",dict[@"sale"]] andUnit:@" 折起"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM月dd日"];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dict[@"startTime"] longLongValue]];
    cell.brandSaleDateLabel.text = [NSString stringWithFormat:@"%@ 开售",[formatter stringFromDate:date]];
    
    return cell;
}

-(BOOL)isCollected:(NSString *)idString {
    BOOL collected;
    collected = NO;
    for (NSString *itemStr in collectionArray) {
        if ([itemStr intValue] == [idString intValue]) {
            collected = YES;
            break ;
        }
    }
    
    return collected;
}

-(void)collectBrandClicked:(UIButton *)button {
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSString *memberId = dataDic[@"memberId"];
    NSString *token = dataDic[@"token"];
    if ([CheckLoginObject isLogin]) {//token 正确
        NSDictionary *dict = [comingSpecialArray objectAtIndex:button.tag];
        NSDictionary *userD = [NSDictionary dictionaryWithObjectsAndKeys:memberId,@"memberid",token,@"access_token",[NSString stringWithFormat:@"%@",dict[@"id"]],@"specialid", nil];
        if (button.selected == YES) { //已收藏
            [self deleteCollectedItem:userD button:button];
        } else {
            [self addToCollectionItem:userD button:button];
        }
       
    } else {
         [self login]; //未登录/登录失败/token过期
    }
    
}
//添加收藏
-(void)addToCollectionItem:(NSDictionary *)parameterDict button:(UIButton *)itemButton {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:APIURL"sale/addToCollection.json" parameters:parameterDict success:^(AFHTTPRequestOperation *operation,id resultObject){
        if ([resultObject[@"isOk"] intValue] > 0) {
            itemButton.selected = YES;
        }
        [self requestCollectedListArray];
            
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        
    }];
    
}
//取消收藏
-(void)deleteCollectedItem:(NSDictionary *)parameterDict button:(UIButton *)itemButton{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:APIURL"sale/deleteFromCollection.json" parameters:parameterDict success:^(AFHTTPRequestOperation *operation,id resultObject){
        if ([resultObject[@"isOk"] intValue] > 0) {
            itemButton.selected = NO;
        }
        [self requestCollectedListArray];
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        
    }];
}

#pragma mark login
- (void)login{
    logOnViewController *loginVC = (logOnViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"logOnViewController"];
    UINavigationController *navigationVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    
    navigationVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navigationVC.navigationBar.tintColor = [UIColor blackColor];
    // present
    [self presentViewController:navigationVC animated:YES completion:nil];
}

-(NSMutableAttributedString *)returenDisCountString:(NSString *)count andUnit:(NSString *)unit {
    NSMutableAttributedString *attring = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",count,unit]];
    [attring addAttribute:NSForegroundColorAttributeName value:ColorFromRGB(0xff0100) range:NSMakeRange(0, count.length)];
    [attring addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"ArialRoundedMTBold" size:16] range:NSMakeRange(0, count.length)];
    [attring addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(count.length, unit.length)];
    [attring addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:11] range:NSMakeRange(count.length, unit.length)];
    
    
    return attring;
}

#pragma mark UICollectionView delegate
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *view = (UICollectionReusableView *)[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"reuserview" forIndexPath:indexPath];
    view.backgroundColor = [UIColor clearColor];
    UILabel *titleLabel = (UILabel *)[view viewWithTag:101];
    UILabel *detailLabel = (UILabel *)[view viewWithTag:1001];
    titleLabel.textColor = ColorFromRGB(0x52525c);
    detailLabel.textColor = RGBA(132, 132, 132, 1);
    if (indexPath.section == 0) {
        titleLabel.frame = CGRectMake(8, 5, 75, 21);
        detailLabel.hidden = YES;
        titleLabel.hidden = NO;
        titleLabel.text = @"今日特卖";
    } else if (indexPath.section == 2){
        detailLabel.frame = CGRectMake(88, 8, 222, 16);
        titleLabel.frame = CGRectMake(8, 5, 75, 21);
        detailLabel.hidden = NO;
        titleLabel.hidden = NO;
        detailLabel.text = @"马上收藏您喜欢的品牌，开售当天通知您";
        titleLabel.text = @"下期特卖";
    
    } else {
        titleLabel.hidden = YES;
        detailLabel.hidden = YES;
    }
    
    return view;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict;
    if (indexPath.section == 0) {
        dict = [startedSpecialArray objectAtIndex:indexPath.row];
        
    } else if (indexPath.section == 2 || indexPath.row == 1) {
        return ;
//        dict = [comingSpecialArray objectAtIndex:indexPath.row];
    }
    BrandListVC *brandVC = [self.storyboard instantiateViewControllerWithIdentifier:@"BrandListVC"];
    [brandVC setSpecialId:[NSString stringWithFormat:@"%@",dict[@"urlId"]]];
    [brandVC setSortString:[NSString stringWithFormat:@"%@",dict[@"sort"]]];
    [brandVC setTitleString:dict[@"word"]];
    [self.navigationController pushViewController:brandVC animated:YES];
}

#pragma mark UIScrollView Delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [headerView egoRefreshScrollViewDidScroll:scrollView];
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isRefresh = NO;
    [headerView egoRefreshScrollViewDidEndDragging:scrollView];
}


#pragma mark EGORefresHeaderView Delegate
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view {
    return isRefresh;
}
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view {
    return [NSDate date];
}
-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view {
    isRefresh = YES;
    [self performSelector:@selector(requestBrandListDataFromNet) withObject:nil afterDelay:0];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"toPersonCenter"]) {
        
    } else if ([segue.identifier isEqualToString:@"toCart"]) {
        
    }
    
}
//是否可以通过segu跳转
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    if ([identifier isEqualToString:@"toCart"]) {
        if (![CheckLoginObject isLogin]) {  //未登录/登录失败/token过期
            [self login];
            return NO;
        }
    }
    return YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (startedSpecialArray.count == 0 && comingSpecialArray.count == 0) {
        [self requestCollectedListArray];
        [self requestBrandListDataFromNet];
    }
}

#pragma mark buttonClicked methods
- (IBAction)rightButtonClicked:(UIButton *)sender {
    
}
- (IBAction)leftButtonClicked:(UIButton *)sender {
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
